package org.itboys.seller.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.itboys.admin.dto.AdminUserDTO;
import org.itboys.admin.dto.AdminUserData;
import org.itboys.admin.entity.AdminUser;
import org.itboys.admin.entity.AdminUserOrgPost;
import org.itboys.admin.entity.GlobalConfigDB;
import org.itboys.admin.service.AdminUserService;
import org.itboys.admin.service.GlobalConfigService;
import org.itboys.commons.utils.cookie.CookieUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.entity.EntityIdDB;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.service.IDGeneratorService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.redis.RedisCacheClient;
import org.itboys.seller.constant.*;
import org.itboys.seller.dto.SiteUserVO;
import org.itboys.seller.entity.*;
import org.itboys.seller.meta.*;
import org.itboys.seller.utils.SellerSessionHolder;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商家登陆账号
 * @author weisky
 *
 */
@Service
public class CaliforniaSiteUserService extends BaseService<SiteUser, Long>{
	
	private static final long serialVersionUID = 1L;

    private static final String SHOP_ID_KEY = "USER_SHOP_ID-";
    private static final int SHOP_ID_EXPIRE = 24 * 3600;

	@Resource(name = "sellerDS")
	private MongoDataSource ds;
	
	@Autowired
	private ResourceHolder resourceHolder;
    @Autowired
    private RedisCacheClient redisCacheClient;
	@Autowired
	private IDGeneratorService idGeneratorService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private GlobalConfigService globalConfigService;
	@Autowired
	private RankingUserService rankingUserService;
	@Resource
	private SellerUserService sellerUserService;
	@Resource
	private AdminUserService adminUserService;
	@Resource
	private RewardRecordService rewardRecordService;
    @Resource
    private GetRewardRecordService getRewardRecordService;
    @Resource
    private UserChargerService userChargerService;
    @Resource
    private SubManProviderService subManProviderService;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<SiteUser> getEntityClass() {
		return SiteUser.class;
	}

	public void modifyPass(Long userId, String newPassword) {
		SiteUser au = getAdminUserByUserId(userId);
		au.setPassword(Digests.md5(newPassword));
		update(au);
	}

	/**
	 * 修改或保存
	 * @param sellerUser
	 * @return 0:系统错误  1：成功  2：用户名已存在
	 */
	public int insert(SiteUser sellerUser){
		try{
			sellerUser.setPassword(Digests.md5(sellerUser.getPassword()));//将密码转换成MD5加密
			
			if(sellerUser.getId() != 0){//修改
                SiteUser sellerUser2 = getById(sellerUser.getId());
				if(StringUtils.equals(Digests.md5(""), sellerUser.getPassword())){//密码为空
					sellerUser.setPassword(sellerUser2.getPassword());//若是密码为空  就设置成原来的密码
				}
				update(sellerUser);
			}else{//新增
                sellerUser.setState(CaliforniaSiteConstant.TYPE_ONE);
				save(sellerUser);
//                addPersons(sellerUser);
			}
			return 1;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.insert error", e);
			return 0;//失败
		}
	}

    private void addPersons(SiteUser sellerUser) {
        Query<SiteUser> query = getMongoDataSource().createQuery(SiteUser.class);
        UpdateOperations<SiteUser> ops = getMongoDataSource().createUpdateOperations(SiteUser.class);
        SiteUser parent;
        if (sellerUser.getRecUserId() != 0) {
            parent = getByField("userId", sellerUser.getRecUserId());
            logger.info("account {} add one direct count.", parent.getUserId());

            while (parent != null) {
//                update(parent.getId(), "groupCount", parent.getGroupCount() + 1);
                logger.info("account {} add one group count.", parent.getUserId());
                parent = getByField("userId", parent.getRecUserId());
            }
        }
    }
	
	/**
	 * 修改商家账号的状态
	 * @param sellerUserId
	 * @param state 0：冻结  1：开通
	 * @return
	 */
	public boolean updateState(Long sellerUserId, int state){
		try{
			update(sellerUserId, "state", state);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.updateState error", e);
			return false;
		}
	}
	
	/**
	 * 登陆
	 * @param userName
	 * @param password
	 * @param response
	 * @return
	 */
	public int login(String userName, String password, HttpServletResponse response){
		try{

            SiteUser sellerUser = getByField("accountId", userName);
			if(sellerUser == null){
				return -1;//用户不存在
			}
			if(SellerConstants.ACCOUNT_FROZEN == sellerUser.getState()){//账号被冻结
				return -3;
			}
			if(!StringUtils.equals(sellerUser.getPassword(), Digests.md5(password))){
				logger.warn("商家账号登陆异常：账号名："+userName+"，登陆密码："+password+"，密码不匹配");
				return -2;//密码不正确
			}
			sellerUser.setLoginTime(System.currentTimeMillis());//登陆时间
			sellerUser.setLoginIp(SellerSessionHolder.getLoginIp());//登陆IP
			update(sellerUser);//修改登陆人的登陆时间和IP
			
			CookieUtils.addCookie(response, SellerCookieConstant.COOKIE_USER_NAME, userName, 864000);
			ServletContextHolder.getSession().setAttribute(SellerSessionConstant.SESSION_USER_ID, sellerUser.getId());
			ServletContextHolder.getSession().setAttribute(SellerSessionConstant.SITE_ACCOUNT_ID, sellerUser.getUserId());
			ServletContextHolder.getSession().setMaxInactiveInterval(Integer.valueOf(resourceHolder.getStringValue("sessionMaxInactiveInterval")));//设置session有效时间
			return SellerConstants.ACTION_SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.login error", e);
			return SellerConstants.ACTION_FAIL;//操作失败
		}
	}

	/**
	 * 删除
	 * @param sellerUserId
	 * @return
	 */
	public boolean dele(Long sellerUserId){
		try{
			super.delete(sellerUserId);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.dele error", e);
			return false;
		}
	}

    /**
     * 根据用户名查询用户
     *
     * @return
     */
    public SiteUser getAdminUser(String memberName) {
        // 用户名转小写再查
        List<SiteUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("memberName", memberName).asList();
        return list==null||list.isEmpty()?null:list.get(0);
    }

	/**
	 * 根据用户名查询用户
	 *
	 * @return
	 */
	public SiteUser getAdminUserByUserId(long userId) {
		// 用户名转小写再查
		List<SiteUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("userId", userId).asList();
		return list==null||list.isEmpty()?null:list.get(0);
	}

	/**
	 * 根据用户名查询用户
	 *
	 * @return
	 */
	public List<SiteUser> getAdminUserByUserIds(List<Long> userIds) {
		if (CollectionUtils.isEmpty(userIds)) {
			return Collections.emptyList();
		}
		return ds.createQuery(getEntityClass()).field("userId").in(userIds).asList();
	}

	/**
	 * 根据用户名查询用户
	 *
	 * @return
	 */
	public List<SiteUser> findUsers(String memberName, String realName, String phone) {
		if (StringUtils.isBlank(memberName) && StringUtils.isBlank(realName) && StringUtils.isBlank(phone)) {
			return Collections.emptyList();
		}
		Query<SiteUser> query = ds.createQuery(getEntityClass());
		if (StringUtils.isNotBlank(memberName)) {
			query.field("memberName").contains(memberName);
		}
		if (StringUtils.isNotBlank(realName)) {
			query.field("realName").contains(realName);
		}
		if (StringUtils.isNotBlank(phone)) {
			query.field("phone").contains(phone);
		}
		return query.asList();
	}

	/**
	 * 根据用户名查询用户
	 *
	 * @return
	 */
	public List<SiteUser> getRecUserByUserId(long userId) {
		return ds.createQuery(getEntityClass()).field("recUserId").equal(userId).asList();
	}

	/**
	 * 根据手机号查询用户
	 *
	 * @return
	 */
	public SiteUser getAdminUserByPhone(String phone) {
		// 用户名转小写再查
		List<SiteUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("phone", phone).asList();
		return list==null||list.isEmpty()?null:list.get(0);
	}

    public String getHQAccount(String accountId) {
        return "HQ" + accountId;
    }

	public long genUid() {
		Query<EntityIdDB> q = ds.createQuery(EntityIdDB.class);
		UpdateOperations<EntityIdDB> update = ds.createUpdateOperations(EntityIdDB.class).inc("currentId");
		EntityIdDB counter = ds.findAndModify(q, update, false, true);
		return idGeneratorService.getNextId(counter.getCurrentId());
	}

	public void updateChargeTime(long userId) {
		Query<SiteUser> query = ds.createQuery(SiteUser.class).field("userId").equal(userId);
		UpdateOperations<SiteUser> operations = ds.createUpdateOperations(SiteUser.class).set("chargeTime", System.currentTimeMillis());
		ds.update(query, operations);
	}

    public void freeAccount(String accountId) {
        SiteUser sellerUser = getByField("accountId", accountId);
        if (sellerUser != null) {
            sellerUser.setState(CaliforniaSiteConstant.TYPE_ZERO);
            update(sellerUser);
        }
    }

	public void freezeByUserId(long userId, boolean freeze) {
		SiteUser sellerUser = getByField("userId", userId);
		if (sellerUser != null) {
			sellerUser.setFreezen(freeze);
			update(sellerUser);
		}
	}

    public List<SiteUser> getByAccountId(List<String> accountIds) {
        if (CollectionUtils.isEmpty(accountIds)) {
            return Collections.emptyList();
        }
        return ds.createQuery(getEntityClass()).field("accountId").in(accountIds).asList();
    }

	public List<SiteUser> queryInfo(String sellerUserName, int offset, int limit) {
		return ds.createQuery(getEntityClass()).field("sellerUserName").equal(sellerUserName).offset(offset).limit(limit).order("-ct").asList();

	}

	public long totalInfo(String sellerUserName) {
		return ds.createQuery(getEntityClass()).field("sellerUserName").equal(sellerUserName).countAll();
	}

	public List<SiteUser> batchQuerySiteUser() {
		List<SiteUser> allSiteUserList = Lists.newArrayList();
		Query<SiteUser> query = ds.createQuery(getEntityClass()).order("-chargeTime");
		int offset = 0;
		int limit = 200;
		query.offset(offset);
		query.limit(limit);
		List<SiteUser> siteUserList = query.asList();
		allSiteUserList.addAll(siteUserList);
		while (CollectionUtils.isNotEmpty(siteUserList)) {
			query.offset(offset);
			query.limit(limit);
			siteUserList = query.asList();
			offset += limit;
		}
		return allSiteUserList;
	}

	private static final Comparator<SiteUser> SCORE_COMPARATOR = new Comparator<SiteUser>() {
		@Override
		public int compare(SiteUser o1, SiteUser o2) {
			if (o1.getActualScore() <= o2.getActualScore()) {
				return 1;
			} else {
				return -1;
			}
		}
	};

	@Transactional
	public void startMatchJob(AdminUser adminUser, Map<String, GlobalConfigDB> globalConfigDBMap,
                              boolean needShare) {
        GlobalConfigDB rewardLint = globalConfigDBMap.get(GlobalConfigConstants.REWARD_LINE);
        GlobalConfigDB minScore = globalConfigDBMap.get(GlobalConfigConstants.MIN_SCORE);
        GlobalConfigDB dayRecharge = globalConfigDBMap.get(GlobalConfigConstants.DAY_RECHARGE);

        List<Account> accounts = accountService.getAll();
        for (Account account : accounts) {
            userChargerService.updateOrInsert(account.getUserId(), account.getRecentAmount());
        }

		final int recentTotalAmount = accountService.getRecentTotalAmount();
        logger.info("recentTotal {}", recentTotalAmount);
		calculateActualScore(adminUser.getUsername(), recentTotalAmount, needShare);
		int rewardBalance = recentTotalAmount + adminUser.getRewardBalance();
		if (needShare && recentTotalAmount + adminUser.getRewardBalance() >= rewardLint.getValue()) {
			rewardBalance = shareOutBonus(adminUser, recentTotalAmount + adminUser.getRewardBalance(),
                    rewardLint.getValue(), minScore.getValue(), 1, dayRecharge.getValue());
		}
        adminUser.setRewardBalance(rewardBalance);

        rewardLint = globalConfigDBMap.get(GlobalConfigConstants.S_REWARD_LINE);
        rewardBalance = recentTotalAmount + adminUser.getRewardBalanceS();
        minScore = globalConfigDBMap.get(GlobalConfigConstants.S_MIN_SCORE);
        if (needShare && rewardBalance >= rewardLint.getValue()) {
            rewardBalance = shareOutBonus(adminUser, rewardBalance, rewardLint.getValue(),
                    minScore.getValue(), 2, dayRecharge.getValue());
        }
        adminUser.setRewardBalanceS(rewardBalance);

        rewardLint = globalConfigDBMap.get(GlobalConfigConstants.SS_REWARD_LINE);
        minScore = globalConfigDBMap.get(GlobalConfigConstants.SS_MIN_SCORE);
        rewardBalance = recentTotalAmount + adminUser.getRewardBalanceSS();
        if (needShare && rewardBalance >= rewardLint.getValue()) {
            rewardBalance = shareOutBonus(adminUser, rewardBalance, rewardLint.getValue(),
                    minScore.getValue(), 3, dayRecharge.getValue());
        }
        adminUser.setRewardBalanceSS(rewardBalance);

		accountService.emptyRecentAmount();

		// 清空管理员当期销售额,记录这一期奖池余额
		adminUser.setLastTotalAmount(recentTotalAmount);
		adminUser.setRecentTotalAmount(0);

		adminUserService.update(adminUser);
	}

	/**
	 * 根据有效积分进行排名
     * @return
     */
	private void calculateActualScore(String sellerUserName, int recentTotalAmount, boolean needShare) {
		List<Account> accountList = accountService.getRankingUsers();
		RankingUserDB rankingUserDB = new RankingUserDB();
		rankingUserDB.setSellerUserName(sellerUserName);
		List<Long> rankingUserIds = Lists.newArrayList();
		Map<Long, Integer> actualScoreMap = Maps.newHashMap();
		Map<Long, Integer> totalScoreMap = Maps.newHashMap();
		for (Account account : accountList) {
			rankingUserIds.add(account.getUserId());
			actualScoreMap.put(account.getUserId(), account.getRecentScore());
			totalScoreMap.put(account.getUserId(), account.getScore());
		}
		rankingUserDB.setUserIds(rankingUserIds);
		rankingUserDB.setActualScores(actualScoreMap);
		rankingUserDB.setTotalScores(totalScoreMap);

        accountList = accountService.getSRankingUsers();
        rankingUserIds = Lists.newArrayList();
        actualScoreMap = Maps.newHashMap();
        totalScoreMap = Maps.newHashMap();
        for (Account account : accountList) {
            if (getRewardRecordService.getByField("userId", account.getUserId()) != null) {
                logger.info("user {} got reward, last rank skip", account.getUserId());
                continue;
            }
            rankingUserIds.add(account.getUserId());
            actualScoreMap.put(account.getUserId(), account.getRecentScoreS());
            totalScoreMap.put(account.getUserId(), account.getScore());
            if (rankingUserIds.size() >= 20) {
                break;
            }
        }
        rankingUserDB.setsUserIds(rankingUserIds);
        rankingUserDB.setsActualScores(actualScoreMap);
        rankingUserDB.setsTotalScores(totalScoreMap);

        accountList = accountService.getSSRankingUsers();
        rankingUserIds = Lists.newArrayList();
        actualScoreMap = Maps.newHashMap();
        totalScoreMap = Maps.newHashMap();
        for (Account account : accountList) {
            rankingUserIds.add(account.getUserId());
            actualScoreMap.put(account.getUserId(), account.getRecentScoreSs());
            totalScoreMap.put(account.getUserId(), account.getScore());
        }
        rankingUserDB.setSsUserIds(rankingUserIds);
        rankingUserDB.setSsActualScores(actualScoreMap);
        rankingUserDB.setSsTotalScores(totalScoreMap);

		rankingUserDB.setTotalAmount(recentTotalAmount);
		rankingUserDB.setType(needShare ? 0 : 1);
		rankingUserService.save(rankingUserDB);
	}



	/**
	 * 当期销售额大于分奖线时,就进行分红
	 * @param siteUserList
	 * @param totalAmount
	 * @param rewardLint
     */
	private int shareOutBonus (AdminUser adminUser, int totalAmount, int rewardLint,
                               int minScore, int type, int dayRecharge) {
		int sharePersonNum = totalAmount / rewardLint;
		int shareMoney = totalAmount % rewardLint;
		RankingUserDB rankingUserDB = rankingUserService.getLatestRankingUserBySellerUserName(0, adminUser.getUsername());
		if (rankingUserDB == null) {
			return 0;
		}
        logger.info("start share bonus, totalAmount {}, rewardLint {}, minScore {}, dayRecharge {}, type {}",
                totalAmount, rewardLint, minScore, dayRecharge, type);
		List<Long> rewardUserIds;
        if (type == 1) {
            rewardUserIds = rankingUserDB.getUserIds();
        } else if (type == 2) {
            rewardUserIds = rankingUserDB.getsUserIds();
        } else {
            rewardUserIds = rankingUserDB.getSsUserIds();
        }
		//记录每个人被清空的有效积分
		List<Account> accountList = accountService.getByIds(rewardUserIds);
		Map<Long, Account> accountMap = accountList.stream().collect(Collectors.toMap(Account::getUserId, p -> p));
		Map<Long, Integer> cleanScoreMap = Maps.newHashMap();
        List<Long> getRewardList = Lists.newArrayList();
        int num = 0;
		for (Long userId : rewardUserIds) {
			Account account = accountMap.get(userId);
            int recentScore;
            int recharge = 0;
            if (type == 1) {
                recentScore = account.getRecentScore();
                recharge = dayRecharge;
            } else if (type == 2) {
                recentScore = account.getRecentScoreS();
            } else {
                recentScore = account.getRecentScoreSs();
            }
            if (type == 2 && getRewardRecordService.getByField("userId", userId) != null) {
                logger.info("user {} got reward, type {}, now skip", userId, type);
                continue;
            }
            if (recentScore >= minScore && userChargerService.getScoreByUserId(userId) >= recharge) {
                getRewardList.add(userId);
                cleanScoreMap.put(userId, recentScore);
            }
            if (getRewardList.size() >= sharePersonNum) {
                break;
            }
		}
        if (CollectionUtils.isEmpty(getRewardList)) {
            return totalAmount;
        }
		RewardRecordDB rewardRecordDB = new RewardRecordDB();
        if (type == 1) {
            rewardRecordDB.setUserIds(getRewardList);
            rewardRecordDB.setCleanScoreMap(cleanScoreMap);
        } else if (type == 2) {
            rewardRecordDB.setsUserIds(getRewardList);
            rewardRecordDB.setsCleanScoreMap(cleanScoreMap);
        } else {
            rewardRecordDB.setSsUserIds(getRewardList);
            rewardRecordDB.setSsCleanScoreMap(cleanScoreMap);
        }
		rewardRecordService.save(rewardRecordDB);
        if (type == 2) {
            for (long userId : getRewardList) {
                GetRewardRecord rewardRecord = new GetRewardRecord();
                rewardRecord.setUserId(userId);
                getRewardRecordService.save(rewardRecord);
            }
        }

        if (type == 1) {
            for (long userId : getRewardList) {
                userChargerService.emptyScore(userId);
                subManProviderService.clearScore(userId);
            }
        }

		// 分奖后清空获奖人当期积分
        if (type == 1) {
            accountService.emptyScoreAfterShareOutBonus(getRewardList);
        } else if (type == 2) {
            accountService.emptySScoreAfterShareOutBonus(getRewardList);
        } else {
            accountService.emptySSScoreAfterShareOutBonus(getRewardList);
        }
        if (getRewardList.size() < sharePersonNum) {
            shareMoney = shareMoney + (sharePersonNum - getRewardList.size()) * rewardLint;
        }
		return shareMoney;
	}

	/**
	 * 分页查询
	 *
	 * @param id
	 * @return
	 */
	public Page<SiteUserVO> pageQueryAll(HttpServletRequest request) {
		Page<SiteUser> page = pageQuery(request);
		List<SiteUser> siteUserList = page.getData();
		List<Long> userIds = siteUserList.stream().map(SiteUser::getUserId).collect(Collectors.toList());
		List<Long> recUserIds = siteUserList.stream().map(SiteUser::getRecUserId).distinct().collect(Collectors.toList());
        recUserIds.addAll(siteUserList.stream().map(SiteUser::getRecUserId2).distinct().collect(Collectors.toList()));
        List<SiteUser> recSiteUsers = getAdminUserByUserIds(recUserIds);
		Map<Long, SiteUser> recSiteUserMap = recSiteUsers.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
		List<Account> accounts = accountService.batchQueryAccount(userIds);
		Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
		List<SiteUserVO> voList = siteUserList.stream().map(p -> {
			SiteUserVO vo = new SiteUserVO();
			vo.setUserId(p.getUserId());
			vo.setMemberName(p.getMemberName());
			vo.setCompanyName(p.getCompanyName());
			vo.setPhone(p.getPhone());
			vo.setRecUserId(p.getRecUserId());
			vo.setRealName(p.getRealName());
			vo.setIdCard(p.getIdCard());
			Account account = accountMap.get(p.getUserId());
			if (account != null) {
				vo.setAmount(account.getAmount());
				vo.setActualScore(account.getRecentScore());
                vo.setActualSScore(account.getRecentScoreS());
                vo.setActualSSScore(account.getRecentScoreSs());
				vo.setTotalScore(account.getScore());
			}
			SiteUser recSiteUser = recSiteUserMap.get(p.getRecUserId());
			if (recSiteUser != null) {
				vo.setRecMemberName(recSiteUser.getRealName());
			}
            recSiteUser = recSiteUserMap.get(p.getRecUserId2());
            if (recSiteUser != null) {
                vo.setRecMemberName2(recSiteUser.getRealName());
            }
			vo.setFreezen(p.isFreezen());
            vo.setMemberType(p.getMemberType());
            vo.setArea(p.getArea());
			return vo;
		}).collect(Collectors.toList());
		return new Page<SiteUserVO>(voList, page.getPageNo(), page.getPageSize(), page.getTotal());
	}

    public List<SiteUser> getUsersByRecAndType(long recUser, int type) {
        List<SiteUser> users = ds.createQuery(getEntityClass()).field("recUserId").equal(recUser)
                .field("memberType").equal(type).asList();
        if (type == 1 || type == 2) {
            return users;
        }
        users.addAll(ds.createQuery(getEntityClass()).field("recUserId2").equal(recUser)
                .field("memberType").equal(type).asList());
        Queue<SiteUser> queue = new LinkedList<SiteUser>();
        queue.addAll(users);
        SiteUser user;
        List<SiteUser> allUsers = Lists.newArrayList();
        while (!queue.isEmpty()) {
            user = queue.poll();
            allUsers.add(user);
            users = ds.createQuery(getEntityClass()).field("recUserId").equal(user.getUserId())
                    .field("memberType").equal(type).asList();
            if (CollectionUtils.isNotEmpty(users)) {
                queue.addAll(users);
            }
        }
        long secondRecUserId;
        long firstRecUserId;
        SiteUser secondRecUser;
        SiteUser firstRecUser;
        for (int i = allUsers.size() - 1; i >= 0; i--) {
            //判断此user是否该计入到业绩中
            if (allUsers.get(i).getRecUserId2() == 0 || allUsers.get(i).getRecUserId() == 0) {
                continue;
            }
            //找到第一推荐人这一级的最上级服务商
            firstRecUser = getByField("userId", allUsers.get(i).getUserId());
            while (firstRecUser.getRecUserId() != 0) {
                firstRecUserId = firstRecUser.getRecUserId();
                if (firstRecUser.getMemberType() != 0) {
                    break;
                }
                firstRecUser = getByField("userId", firstRecUserId);
            }
            //找到第二推荐人这一级的最上级服务商
            secondRecUser = getByField("userId", allUsers.get(i).getRecUserId2());

            final long firstTmpId = firstRecUser.getUserId();
            final long secondTmpId = secondRecUser.getUserId();
            //判断两个祖先的顺序
            SiteUser tmp1 = firstRecUser;
            SiteUser tmp2 = secondRecUser;
            boolean isFirstAheadSecond = false;
            boolean isSecondAheadSecond = false;
            while (tmp1.getRecUserId() != 0) {
                if (tmp1.getRecUserId() == tmp2.getUserId()) {
                    isSecondAheadSecond = true;
                    break;
                }
                tmp1 = getByField("userId", tmp1.getRecUserId());
            }
            tmp1 = firstRecUser;
            tmp2 = secondRecUser;
            while (tmp2.getRecUserId() != 0) {
                if (tmp2.getRecUserId() == tmp1.getUserId()) {
                    isFirstAheadSecond = true;
                    break;
                }
                tmp1 = getByField("userId", tmp2.getRecUserId());
            }

            if (isFirstAheadSecond) {
                if (allUsers.get(i).getRecUserId2() != recUser) {
                    while (secondRecUser.getRecUserId() != 0) {
                        secondRecUserId = secondRecUser.getRecUserId();
                        if (firstTmpId == secondRecUserId) {
                            allUsers.remove(i);
                            break;
                        }
                        secondRecUser = getByField("userId", secondRecUser.getRecUserId());
                    }
                }
            } else if (isSecondAheadSecond) {
                if (allUsers.get(i).getRecUserId2() == recUser) {
                    allUsers.remove(i);
                }
//                while (firstRecUser.getRecUserId() != 0) {
//                    firstRecUserId = firstRecUser.getRecUserId();
//                    if (secondTmpId == firstRecUserId) {
//                        allUsers.remove(i);
//                        break;
//                    }
//                    firstRecUser = getByField("userId", firstRecUser.getRecUserId());
//                }
            }
        }
        return allUsers;
    }
}
